package com.vframework.system.user.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.util.StringUtil;
import com.vframework.base.controller.BaseController;
import com.vframework.base.exception.BaseException;
import com.vframework.base.model.BaseBean;
import com.vframework.common.constant.SessionConstant;
import com.vframework.system.org.model.OrgBean;
import com.vframework.system.org.service.OrgService;
import com.vframework.system.role.model.RoleBean;
import com.vframework.system.user.model.UserBean;
import com.vframework.system.user.service.UserService;
/***************************************************************
 * Name:        UserController.java
 * Create At:   2018年6月14日
 * Module:      
 * Description: [用户管理-用户管理增删改查功能]
 * @author      zt_sh
 * ------------------------------------------------------------
 * 修改历史
 * 序号         日期                       修改人               修改原因
 * 1    2018年4月14日      zt_sh    
 * 2
***************************************************************/
@Controller
@RequestMapping("UserController")
public class UserController extends BaseController {

    private static final String BATH_PATH = "com/vframework/system/user/pages/";

    @Autowired
    private UserService userService;
    @Autowired
    private OrgService orgService;

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [系统管理-初始页面，查询用户信息列表]
     * 
     * @return String
     */
    @RequestMapping(value = "begin")
    public String begin(Model model) throws Exception {
        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [用户管理-查询用户列表]
     * 
     * @return String
     */
    @RequestMapping(value = "queryList")
    public String queryList(Model model) throws Exception {
        try {
            // 超级管理员可以查看全部
            String orgType = (String) super.session.getAttribute(SessionConstant.SESSION_ORG_TYPE);
            if (!"0".equals(orgType)) {
                super.paramMap.put("param_siId", (String) (super.session.getAttribute(SessionConstant.SESSION_ORG_ID)));
            }
            List<UserBean> resultList = userService.getUserList(super.paramMap);
            model.addAttribute("resultList", resultList);
        } catch (BaseException e) {
            super.message("查询失败: " + e.getMessage());
        }
        return BATH_PATH + "userList";
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [用户管理-点击添加按钮，进入添加页面]
     * 
     * @return String
     */
    @RequestMapping(value = "add")
    public String add(Model model) throws Exception {
        String orgType = (String) super.session.getAttribute(SessionConstant.SESSION_ORG_TYPE);
        if (!"0".equals(orgType)) {
            String orgId = (String) (super.session.getAttribute(SessionConstant.SESSION_ORG_ID));
            super.paramMap.put("param_orgId", orgId);
        }
        List<OrgBean> orgList = orgService.getOrgList(super.paramMap);
        String userId = (String) (super.session.getAttribute(SessionConstant.SESSION_USER_ID));
        super.paramMap.put("param_userId", userId);
        model.addAttribute("orgList", orgList);
        model.addAttribute("userBean", new UserBean());
        model.addAttribute("method", "add");
        return BATH_PATH + "userAdd";
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [用户管理-点击修改按钮，进入修改页面]
     * 
     * @return String
     */
    @RequestMapping(value = "edit")
    @SuppressWarnings("unchecked")
    public String edit(Model model) throws Exception {
        String userId = request.getParameter("userId");
        try {
            UserBean userBean = userService.getUserById(userId);
            List<BaseBean> roleList = null;
            if (!StringUtil.isEmpty(userBean.getOrgId())) {
                List<RoleBean> roleSet = (List<RoleBean>) super.session.getAttribute(SessionConstant.SESSION_USER_ROLE);
                String roleType = "3";
                for (RoleBean role : roleSet) {
                    String temp = role.getRoleType();
                    if (Integer.parseInt(temp) < Integer.parseInt(roleType)) {
                        roleType = temp;
                    }
                }
                paramMap.put("siId", userBean.getOrgId());
                paramMap.put("roleType", roleType);
                roleList = userService.getRoleByOrgId(paramMap);
            }
            String orgType = (String) super.session.getAttribute(SessionConstant.SESSION_ORG_TYPE);
            if (!"0".equals(orgType)) {
                String orgId = (String) super.session.getAttribute(SessionConstant.SESSION_ORG_ID);
                super.paramMap.put("param_orgId", orgId);
            }
            List<OrgBean> orgList = orgService.getOrgList(super.paramMap);
            model.addAttribute("method", "edit");
            model.addAttribute("roleList", roleList);
            model.addAttribute("orgList", orgList);
            model.addAttribute("userBean", userBean);
        } catch (BaseException e) {
            super.message("查询用户信息失败: " + e.getMessage());
            return queryList(model);
        }
        return BATH_PATH + "userAdd";
    }

    @RequestMapping(value = "getRoleListByOrg")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public List<BaseBean> getRoleListByOrg() {
        String orgId = request.getParameter("orgId");
        if (StringUtil.isEmpty(orgId)) {
            return null;
        }
        List<RoleBean> roleSet = (List<RoleBean>) super.session.getAttribute(SessionConstant.SESSION_USER_ROLE);
        String roleType = "3";
        for (RoleBean role : roleSet) {
            String temp = role.getRoleType();
            if (Integer.parseInt(temp) < Integer.parseInt(roleType)) {
                roleType = temp;
            }
        }
        List<BaseBean> roleList = null;
        paramMap.put("siId", orgId);
        paramMap.put("roleType", roleType);
        try {
            roleList = userService.getRoleByOrgId(paramMap);
        } catch (BaseException e) {
            super.message("查询失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return roleList;
    }

    /**
     * Author:shanzhitong Create At:2010-04-22 Description: [用户管理-添加用户，保存用户信息]
     * 
     * @return String
     */
    @RequestMapping(value = "addSave")
    public String addSave(UserBean userBean, Model model) throws Exception {
        try {
            userBean.setOperator((String)super.session.getAttribute(SessionConstant.SESSION_USER_ID));
            userService.addUser(userBean);
            super.message("添加成功！");
            userService.insertLog(super.MakeLogBean(super.LOG_ADD_KEY, "添加用户", userBean.toString()));
        } catch (BaseException e) {
            super.message("添加失败: " + e.getMessage());
        }
        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [用户管理-修改用户，保存用户信息]
     * 
     * @return String
     */
    @RequestMapping(value = "editSave")
    public String editSave(UserBean userBean, Model model) throws Exception {
        if (userBean != null) {
            try {
                userBean.setOperator((String)super.session.getAttribute(SessionConstant.SESSION_USER_ID));
                userService.editUser(userBean);
                super.message("修改成功！");
                userService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "修改用户", userBean.toString()));
            } catch (BaseException e) {
                super.message("修改失败: " + e.getMessage());
            }
        }

        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [用户管理-暂停用户信息]
     * 
     * @return String
     */
    @RequestMapping(value = "pause")
    public String pause(Model model) throws Exception {
        String siId = (String) (super.session.getAttribute(SessionConstant.SESSION_ORG_ID));
        String[] ids = request.getParameterValues("ids");
        super.paramMap.put("ids", ids);
        super.paramMap.put("orgId", siId);
        try {
            userService.pauseUser(super.paramMap);
            super.message("暂停成功！");
            userService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "暂停用户", super.paramMap.toString()));
        } catch (BaseException e) {
            super.message("暂停失败: " + e.getMessage());
        }
        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [用户管理-启动用户信息]
     * 
     * @return String
     */
    @RequestMapping(value = "reStart")
    public String reStart(Model model) throws Exception {
        String siId = (String) (super.session.getAttribute(SessionConstant.SESSION_ORG_ID));
        String[] ids = request.getParameterValues("ids");
        super.paramMap.put("ids", ids);
        super.paramMap.put("orgId", siId);
        try {
            userService.reStartUser(super.paramMap);
            super.message("启用成功！");
            userService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "启用用户", super.paramMap.toString()));
        } catch (BaseException e) {
            super.message("启用失败: " + e.getMessage());
        }
        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description: [用户管理-删除用户信息]
     * 
     * @return String
     */
    @RequestMapping(value = "delete")
    public String delete(Model model) throws Exception {
        String siId = (String) (super.session.getAttribute(SessionConstant.SESSION_ORG_ID));
        String userId = (String) (super.session.getAttribute(SessionConstant.SESSION_USER_ID));
        String[] ids = request.getParameterValues("ids");
        super.paramMap.put("ids", ids);
        super.paramMap.put("siId", siId);
        super.paramMap.put("userId", userId);
        try {
            userService.deleteUser(super.paramMap);
            super.message("删除成功！");
            userService.insertLog(super.MakeLogBean(super.LOG_DELETE_KEY, "删除用户", super.paramMap.toString()));
        } catch (BaseException e) {
            super.message("删除失败: " + e.getMessage());
        }
        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2017-07-05 Description:
     * [系统管理-初始页面，查询用户信息列表,验证用户名不可重复]
     * 
     * @return String
     */
    @RequestMapping(value = "checkReId")
    @ResponseBody
    public String checkReId() throws Exception {
        String userId = "";
        paramMap.put("param_userName", request.getParameter("param_userName"));
        try {
            UserBean userBean = null;
            userBean = userService.getUserByName(super.paramMap);
            if (userBean != null) {
                userId = userBean.getUserId();
            }
        } catch (BaseException e) {
            super.message("校验失败: " + e.getMessage());
        }
        return userId;
    }

    /**
     * Author:shanzhitong Create At:2017-07-06 Description:
     * [系统管理-初始页面，查询用户信息列表,验证用户名不可重复]
     * 
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "checkUserId")
    @ResponseBody
    private Integer checkUserId() throws Exception {
        Integer count = userService.queryTemplateList(super.paramMap);// 获取数据
        return count;
    }

    /**
     * Author:shanzhitong Create At:2011-9-1 Description: [个人资料-用户查看个人资料]
     * 
     * @return String
     */
    @RequestMapping(value = "getPresonInfo")
    public String getPresonInfo(Model model) throws Exception {
        return BATH_PATH + "personInfo";
    }

    /**
     * Author:shanzhitong Create At:2011-9-1 Description: [修改密码-保存密码]
     * 
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "changePassword")
    @ResponseBody
    public String changePassword(Model model) throws Exception {
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String resTxt = "failure";
        if (oldPassword == null || oldPassword.trim().length() == 0 || newPassword == null
                || newPassword.trim().length() == 0) {
            model.addAttribute("message", "请输入旧密码和新密码！");
        } else {
            super.paramMap.put("oldPassword", oldPassword);
            super.paramMap.put("newPassword", newPassword);
            try {
                Integer result = userService.updatePassword(super.paramMap);
                if (result != null && result == 1) {
                    resTxt = "success";
                } else if (result == 0) {
                    resTxt = "incorrectPWD";
                }
            } catch (BaseException e) {
                super.message("修改失败: " + e.getMessage());
            }
        }
        return resTxt;
    }

    /**
     * Author:shanzhitong Create At:2011-9-1 Description: [个人资料-用户修改个人资料]
     * 
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "savePresonInfo")
    public String savePresonInfo(UserBean userBean, Model model) throws Exception {
        String siId = (String) super.session.getAttribute(SessionConstant.SESSION_ORG_ID);
        userBean.setOrgId(siId);
        try {
            userService.savePresonInfo(userBean);
            userService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "修改个人资料", userBean.toString()));
            super.message("修改成功！");
            if (userBean.getEmail() != null) {
                session.setAttribute("USER_EMAIL", userBean.getEmail());
            }
            if (userBean.getMobile() != null) {
                session.setAttribute("USER_MOBILE", userBean.getMobile());
            }
        } catch (BaseException e) {
            super.message("修改失败: " + e.getMessage());
        }
        return getPresonInfo(model);
    }
}